package edu.hda.pt.server.connections.rmi;

import java.io.IOException;
import java.util.Vector;

import edu.hda.pt.utils.connections.rmi.PTClientRMICallbackI;
import edu.hda.pt.utils.connections.rmi.StreamingData;

/**
 * @author Marc Hammerton
 * 
 */
public class StreamThread extends Thread {

	private Vector<PTClientRMICallbackI> clients = new Vector<PTClientRMICallbackI>();

	private int fileSize = 0;

	/**
	 * Sets the file size which should be sent to the client
	 * 
	 * @param filesize
	 *            - the fileSize to set
	 */
	public void setFileSize(int fileSize) {
		this.fileSize = fileSize;
	}

	/**
	 * Returns the file size
	 * 
	 * @return the file size
	 */
	public int getFileSize() {
		return fileSize;
	}

	/**
	 * Adds a new client
	 * 
	 * @param client
	 *            - the client to be add
	 */
	public void addClient(PTClientRMICallbackI client) {
		this.clients.add(client);
	}

	/**
	 * Removes an existing client
	 * 
	 * @param client
	 *            - the client to be removed
	 */
	public void removeClient(PTClientRMICallbackI client) {
		this.clients.remove(client);
	}

	/**
	 * While the thread is not interrupted, it checks if a client exists. In
	 * this case, it sends a message of the size fileSize to the client. If no
	 * client exists, it waits until it is notified.
	 */
	@Override
	public void run() {

		StreamingData streamingData = new StreamingData();

		while (!isInterrupted()) {
			if (clients.size() == 0) {
				this.fileSize = 0;
				try {
					synchronized (this) {
						this.wait();
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			} else {
				byte[] data = new byte[this.fileSize];
				streamingData.setData(data);
				synchronized (clients) {
					for (PTClientRMICallbackI client : clients) {
						try {
							client.handleStream(streamingData);
						} catch (IOException e1) {
							e1.printStackTrace();
						}
					}
				}
			}
		}

	}

	/**
	 * @see java.lang.Thread#interrupt()
	 */
	@Override
	public void interrupt() {
		super.interrupt();
	}

}
